package com.espressif.espblufi.ui;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.espressif.espblufi.R;
import com.espressif.espblufi.app.BlufiApp;
import com.espressif.espblufi.bean.GroupDevice;
import com.espressif.espblufi.constants.BlufiConstants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

/**
 * =============================================================
 * <p/>
 * Copyright  : Personal Creation All (c) 2018
 * <p/>
 * Author      : Heaven
 * <p/>
 * Version     : 1.0
 * Date of creation : 2018/12/22 17:40.
 * <p/>
 * Description  :
 * <p/>
 * <p/>
 * Revision history :
 * <p/>
 * =============================================================
 */
public class BlueWifiSetting extends AppCompatActivity {

    private Button mBtnNext = null;
    private ImageView mImgBack = null;
    private EditText mEtWifiName = null;
    private EditText mEtWifiPass = null;
    private EditText mEtMeshId1 = null;
    private EditText mEtMeshId2 = null;
    private EditText mEtMeshId3 = null;
    private EditText mEtMeshId4 = null;
    private EditText mEtMeshId5 = null;
    private EditText mEtMeshId6 = null;
    private BluetoothDevice mDevice = null;
    private SharedPreferences sp = null;
    private GroupDevice mGroupDevice;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blue_wifi_setting);
        initView();
        initSetting();
    }

    private void initView() {
        mBtnNext = findViewById(R.id.bt_next_connect);
        mImgBack = findViewById(R.id.iv_back);
        mEtWifiName = findViewById(R.id.et_wifi_name);
        mEtWifiPass = findViewById(R.id.et_wifi_pass);
        mEtMeshId1 = findViewById(R.id.et_mesh_1);
        mEtMeshId1.addTextChangedListener(new EdtTextWatcher());
        mEtMeshId2 = findViewById(R.id.et_mesh_2);
        mEtMeshId2.addTextChangedListener(new EdtTextWatcher());
        mEtMeshId3 = findViewById(R.id.et_mesh_3);
        mEtMeshId3.addTextChangedListener(new EdtTextWatcher());
        mEtMeshId4 = findViewById(R.id.et_mesh_4);
        mEtMeshId4.addTextChangedListener(new EdtTextWatcher());
        mEtMeshId5 = findViewById(R.id.et_mesh_5);
        mEtMeshId5.addTextChangedListener(new EdtTextWatcher());
        mEtMeshId6 = findViewById(R.id.et_mesh_6);
        mEtMeshId6.addTextChangedListener(new EdtTextWatcher());

        mEtWifiName.setText(getConnectWifiSsid());
    }

    private String getMeshId() {
        String mesh1 = mEtMeshId1.getText().toString().trim();
        String mesh2 = mEtMeshId2.getText().toString().trim();
        String mesh3 = mEtMeshId3.getText().toString().trim();
        String mesh4 = mEtMeshId4.getText().toString().trim();
        String mesh5 = mEtMeshId5.getText().toString().trim();
        String mesh6 = mEtMeshId6.getText().toString().trim();
        String meshId = mesh1 + ":" + mesh2 + ":" + mesh3 + ":" + mesh4 + ":" + mesh5 + ":" + mesh6;
        return meshId;
    }

    private void setMeshId(String meshId) {
        if (meshId.isEmpty()) {
            return;
        }
        String[] mesh = meshId.split(":");
        mEtMeshId1.setText(mesh[0]);
        mEtMeshId2.setText(mesh[1]);
        mEtMeshId3.setText(mesh[2]);
        mEtMeshId4.setText(mesh[3]);
        mEtMeshId5.setText(mesh[4]);
        mEtMeshId6.setText(mesh[5]);
    }

    private void initSetting() {

        sp = getSharedPreferences("config", MODE_PRIVATE);
        String meshId = sp.getString("mesh_id", "");
        String wifiPass = sp.getString("wifi_pass", null);
        setMeshId(meshId);
        mEtWifiPass.setText(wifiPass);
        mDevice = getIntent().getParcelableExtra(BlufiConstants.KEY_BLE_DEVICE);
        mGroupDevice = (GroupDevice) getIntent().getSerializableExtra(BlufiConstants.KEY_BLE_LINK);

        mBtnNext.setOnClickListener(new BtnToConnectDevice());
        mImgBack.setOnClickListener(new BtnToConnectDevice());

        ToggleButton togglePwd = findViewById(R.id.togglePwd);

        togglePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //如果选中，显示密码
                    mEtWifiPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    togglePwd.setBackground(getDrawable(R.mipmap.eye_open));
                } else {
                    //否则隐藏密码
                    mEtWifiPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    togglePwd.setBackground(getDrawable(R.mipmap.eye_close));
                }
            }
        });
    }

    private class EdtTextWatcher implements TextWatcher {

        private Handler handler = new Handler();
        String beforeText = "";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            beforeText = s.toString();
            Log.e("BlueWifiSetting : ", "beforeTextChanged: " + s);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("BlueWifiSetting : ", "onTextChanged: " + s);
        }

        @Override
        public void afterTextChanged(final Editable s) {

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    String text = s.toString();
                    if (s.toString().length() == 0) {

                        s.append("00");
                    } else if (s.toString().length() == 1) {
                        text = "0" + s;
                        Log.e("BlueWifiSetting ", "text :" + text);
                        s.clear();
                        s.append(text);
                    }
                }
            }, 3000);
            Log.e("BlueWifiSetting : ", "afterTextChanged: " + s);
        }
    }

    private class BtnToConnectDevice implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.iv_back:
                    finish();
                    break;
                case R.id.bt_next_connect:

                    mGroupDevice.setMesh_id(getMeshId());

                    if (getMeshId().length() < 12) {
                        Toast.makeText(BlueWifiSetting.this, "Wait a moment ... ", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    sp.edit().putString("mesh_id", getMeshId()).apply();

                    String wifiName = mEtWifiName.getText().toString().trim();
                    byte[] wifiLen = wifiName.getBytes();
                    if (wifiLen.length > 31) {
                        Toast.makeText(BlueWifiSetting.this, "The length of wifi name are too large .", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mGroupDevice.setSsid(mEtWifiName.getText().toString().trim());
                    String wifiPass = mEtWifiPass.getText().toString().trim();
                    byte[] passLen = wifiPass.getBytes();
                    if (passLen.length > 63) {
                        Toast.makeText(BlueWifiSetting.this, "The length of wifi pass are too large . ", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (wifiPass.isEmpty()) {
                        Toast.makeText(BlueWifiSetting.this, "Current wifi password is empty .", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mGroupDevice.setPassword(mEtWifiPass.getText().toString().trim());
                    sp.edit().putString("wifi_pass", mEtWifiPass.getText().toString().trim()).apply();

                    Gson gson = new Gson();
                    String linkDevice = gson.toJson(mGroupDevice);
                    Log.e(" BlueWifiSetting : ", "linkDevice:" + linkDevice);
                    sp.edit().putString("group", linkDevice).apply();

                    Intent intent = new Intent(BlueWifiSetting.this, BlufiActivity.class);
                    intent.putExtra(BlufiConstants.KEY_BLE_DEVICE, mDevice);
//                    startActivityForResult(intent, REQUEST_BLUFI);

                    startActivity(intent);
                    break;
            }
        }
    }

    private String getConnectWifiSsid() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String wifiName = wifiInfo.getSSID();
        String reslut = wifiName.substring(1, wifiName.length() - 1);
        return reslut;
    }

}

